package com.bbx.taxi.client.widget.pop;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.bbx.taxi.official.R;
import com.bbx.taxi.client.MyApplication.OnLocationResultListener;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Util.DateFormat;
import com.example.mydatepicker.adapter.NumericWheelAdapter;
import com.example.mydatepicker.wheelview.OnWheelScrollListener;
import com.example.mydatepicker.wheelview.WheelView;

public class DatePicker {
	int estimate_time=0;
	private PopupWindow mPopupWindow_date;
	private PopupWindow mPopupWindow_date2;
	private PopupWindow mPopupWindow_people;
	private LayoutInflater inflater = null;
	private WheelView day;
	private WheelView time;
	private WheelView hour;
	private WheelView min;
	private WheelView empty;
	private WheelView people;
	private int mYear = 1996;
	private int mMonth = 0;
	private int mDay = 1;
	private int mHour;
	private int mMinute;
	private Context context;
	public static DatePicker mDatePicker;

	public static DatePicker getInstance(Context context) {
		if (mDatePicker == null) {
			mDatePicker = new DatePicker(context);
			return mDatePicker;

		} else
			return mDatePicker;
	}

	public DatePicker(Context context) {
		this.context = context;
		inflater = LayoutInflater.from(context);
	}

	/**
	 * 显示滚轮控件， 0为（完整时间，包含接机） 1为 （如：4月24号今天） 2为人数
	 */
	public void onShow(View v, int type) {
		if(!mOnPoPViewStateListenerlist.isEmpty()){
			for(int i=0;i<mOnPoPViewStateListenerlist.size();i++){
				mOnPoPViewStateListenerlist.get(i).onPopViewState(true);
			}
		}
		switch (type) {
		case 1:
			initCurrentDate();
			initDatePopView(1);
			mPopupWindow_date.showAtLocation(v, Gravity.BOTTOM, 0, 0);
			break;
		case 2:
			initCurrentDate();
			initDatePopView(2);
			mPopupWindow_date.showAtLocation(v, Gravity.BOTTOM, 0, 0);
			break;
		case 3:
			initDatePopView2();
			mPopupWindow_date2.showAtLocation(v, Gravity.BOTTOM, 0, 0);
			break;
		case 4:
			initPeoplePopView(12,null);
			mPopupWindow_people.showAtLocation(v, Gravity.BOTTOM, 0, 0);
			break;
		}
	}
	/**
	 * 显示滚轮控件， 默认为人数
	 */
	public void onShowPeople(View v,int num,String text) {
		if(!mOnPoPViewStateListenerlist.isEmpty()){
			for(int i=0;i<mOnPoPViewStateListenerlist.size();i++){
				mOnPoPViewStateListenerlist.get(i).onPopViewState(true);
			}
		}
		initPeoplePopView( num, text);
		mPopupWindow_people.showAtLocation(v, Gravity.BOTTOM, 0, 0);
	}
	/**
	 * 日期popView(包含小时跟分)
	 */
	public void initDatePopView(int type) {
		View popview = getDataPick(type);
		mPopupWindow_date = new PopupWindow(popview, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		mPopupWindow_date.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow_date.setContentView(popview);
		mPopupWindow_date.setOutsideTouchable(false);
		mPopupWindow_date.setFocusable(true);
		mPopupWindow_date.setAnimationStyle(R.style.mypopwindow_anim_style);
		mPopupWindow_date.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				if(!mOnPoPViewStateListenerlist.isEmpty()){
					for(int i=0;i<mOnPoPViewStateListenerlist.size();i++){
						mOnPoPViewStateListenerlist.get(i).onPopViewState(false);
					}
				}
			}
		});
	}

	/**
	 * 日期popView(不包含时间)
	 */
	public void initDatePopView2() {
		View view = inflater.inflate(R.layout.wheel_date2_picker, null);
		((TextView) view.findViewById(R.id.tv_cancel))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPopupWindow_date2.dismiss();
					}
				});
		((TextView) view.findViewById(R.id.tv_confirm))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPopupWindow_date2.dismiss();
						if (mOnConfirmListener != null) {
							mOnConfirmListener.onConfirm(list, day);
						}
					}
				});
		day = (WheelView) view.findViewById(R.id.day);
		initDay2(mYear, mMonth, mDay);
		day.setCyclic(false);
		day.addScrollingListener(scrollListener);// 设置显示行数
		day.setVisibleItems(7);
		mPopupWindow_date2 = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		mPopupWindow_date2.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow_date2.setContentView(view);
		mPopupWindow_date2.setOutsideTouchable(false);
		mPopupWindow_date2.setFocusable(true);
		mPopupWindow_date2.setAnimationStyle(R.style.mypopwindow_anim_style);
		mPopupWindow_date2.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				if(!mOnPoPViewStateListenerlist.isEmpty()){
					for(int i=0;i<mOnPoPViewStateListenerlist.size();i++){
						mOnPoPViewStateListenerlist.get(i).onPopViewState(false);
					}
				}
			}
		});
	}

	/**
	 * 人数popView
	 */
	public void initPeoplePopView(int num,String text) {
		View popview = getPeoplePick(num,text);
		mPopupWindow_people = new PopupWindow(popview,
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		mPopupWindow_people.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow_people.setContentView(popview);
		mPopupWindow_people.setOutsideTouchable(false);
		mPopupWindow_people.setFocusable(true);
		mPopupWindow_people.setAnimationStyle(R.style.mypopwindow_anim_style);
		mPopupWindow_people.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss() {
				if(!mOnPoPViewStateListenerlist.isEmpty()){
					for(int i=0;i<mOnPoPViewStateListenerlist.size();i++){
						mOnPoPViewStateListenerlist.get(i).onPopViewState(false);
					}
				}
			}
		});
	}

	/**
	 * 获取日期控件
	 */
	private View getDataPick(int type) {
		estimate_time=MainAttribute.getInstance().getEstimate_time();
		View view = inflater.inflate(R.layout.wheel_date_picker, null);
		final TextView tv_estimate_time=(TextView)view.findViewById(R.id.tv_estimate_time);
		tv_estimate_time.setText(estimate_time+"");
		((TextView) view.findViewById(R.id.tv_cancel))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPopupWindow_date.dismiss();
					}
				});
		((TextView) view.findViewById(R.id.tv_confirm))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPopupWindow_date.dismiss();
						if (mOnDateConfirmListener != null) {
							mOnDateConfirmListener.onDateConfirm(list,list_min,day,
									hour, min,estimate_time);
						}
					}
				});
		final ImageButton ib_minus = ((ImageButton) view.findViewById(R.id.ib_minus));
		ib_minus.setEnabled(false);
				ib_minus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				estimate_time--;
				if(estimate_time>Value.estimate_time){
					ib_minus.setEnabled(true);
				}else{
					ib_minus.setEnabled(false);
				}
				
				tv_estimate_time.setText(estimate_time+"");
			}
		});
		((ImageButton) view.findViewById(R.id.ib_add))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						ib_minus.setEnabled(true);
						estimate_time++;
						tv_estimate_time.setText(estimate_time+"");
					}
				});
		day = (WheelView) view.findViewById(R.id.day);
		initDay(mYear, mMonth, mDay, type);
		day.setCyclic(false);
		day.addScrollingListener(scrollListener);

		// time= (WheelView) view.findViewById(R.id.time);
		// String[] times = {"上午","下午"} ;
		// ArrayWheelAdapter<String> arrayWheelAdapter=new
		// ArrayWheelAdapter<String>(MainActivity.this,times );
		// time.setViewAdapter(arrayWheelAdapter);
		// time.setCyclic(false);
		// time.addScrollingListener(scrollListener);

		hour = (WheelView) view.findViewById(R.id.hour);
		NumericWheelAdapter numericWheelAdapter3 = new NumericWheelAdapter(
				context, 0, 23, "%2d", type);
		// numericWheelAdapter3.setLabel("时");
		hour.setViewAdapter(numericWheelAdapter3);
		hour.setCyclic(true);
		hour.addScrollingListener(scrollListener);
		hour.setCurrentItem(type == 1 ? 1 : 0);

		
		//分钟为05，10~55
		min = (WheelView) view.findViewById(R.id.min);
		list_min.clear();
		String s_min[]=new String[]{"-","00","05","10","15","20","25","30","35","40","45","50","55"};
		for(String s:s_min){
			list_min.add(s);
		}
		NumericWheelAdapter numericWheelAdapter4 = new NumericWheelAdapter(
				context, list_min, "%02d", 4);
//		NumericWheelAdapter numericWheelAdapter4 = new NumericWheelAdapter(
//				context, 0, 59, "%2d", type);
		// numericWheelAdapter4.setLabel("分");
		min.setViewAdapter(numericWheelAdapter4);
		min.setCyclic(true);
		min.addScrollingListener(scrollListener);
		min.setCurrentItem(type == 1 ? 1 : 0);

		empty = (WheelView) view.findViewById(R.id.empty);
		List<String> list_empty = new ArrayList<String>();
		list_empty.add("");
		NumericWheelAdapter numericWheelAdapter5 = new NumericWheelAdapter(
				context, list_empty, "%02d", 4);
		empty.setCyclic(true);
		empty.setViewAdapter(numericWheelAdapter5);

		// 设置显示行数
		day.setVisibleItems(7);
		hour.setVisibleItems(7);
		min.setVisibleItems(7);
		empty.setVisibleItems(7);

		return view;
	}

	/**
	 * 获取人数选择控件
	 */
	private View getPeoplePick(int num,String text) {
		View view = inflater.inflate(R.layout.wheel_people_picker, null);
		((TextView) view.findViewById(R.id.tv_cancel))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPopupWindow_people.dismiss();
					}
				});
		((TextView) view.findViewById(R.id.tv_confirm))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mPopupWindow_people.dismiss();
						if (mOnConfirmListener != null) {
							mOnConfirmListener.onConfirm(null, people);
						}
					}
				});
		if(text!=null&&!text.equals("")){
			((TextView) view.findViewById(R.id.tv_notes)).setVisibility(View.VISIBLE);
			((TextView) view.findViewById(R.id.tv_notes)).setText(text);
		}
		people = (WheelView) view.findViewById(R.id.people);
		NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(
				context, 1, num, "%2d");
		people.setViewAdapter(numericWheelAdapter);
		if(num<=5){
			people.setCyclic(false);
		}
		else{
			people.setCyclic(true);
		}

		people.addScrollingListener(scrollListener);
		people.setVisibleItems(7);
		return view;
	}

	OnWheelScrollListener scrollListener = new OnWheelScrollListener() {
		@Override
		public void onScrollingStarted(WheelView wheel) {

		}

		@Override
		public void onScrollingFinished(WheelView wheel) {
			if (wheel == people) {
				if (mOnPeopleScrollResultListener != null) {
					mOnPeopleScrollResultListener.OnPeopleScrollResult(people);
				}
			} else {
				if (mOnDateScrollResultListener != null) {
					mOnDateScrollResultListener.OnDateScrollResult(list,list_min, day,
							hour, min);
				}
			}
		}
	};

	/**
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	private int getDay(int year, int month) {
		int day = 30;
		boolean flag = false;
		switch (year % 4) {
		case 0:
			flag = true;
			break;
		default:
			flag = false;
			break;
		}
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			day = 31;
			break;
		case 2:
			day = flag ? 29 : 28;
			break;
		default:
			day = 30;
			break;
		}
		return day;
	}

	/**
	 * 设置初始时间
	 */
	private void initCurrentDate() {
		long Time = DateFormat.getTime();
		Calendar mCalendar = Calendar.getInstance();
		mCalendar.setTimeInMillis(Time);
		mYear = mCalendar.get(Calendar.YEAR);
		mMonth = mCalendar.get(Calendar.MONTH) + 1;
		mDay = mCalendar.get(Calendar.DAY_OF_MONTH);
		mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
		mMinute = mCalendar.get(Calendar.MINUTE);
	}

	/**
	 * curYear当前年， curMonth当前月（用于含有小时跟分）
	 */
	private void initDay(int curYear, int curMonth, int mDay, int type) {
		Log.e("", curYear + "," + curMonth + "," + mDay + "," + mHour + ","
				+ mMinute);
		list.clear();
		int max=5;
		if(getDay(curYear, curMonth)<mDay+max-1){
			addDayList(curYear, curMonth, mDay, false, true);// 第一个月
			if( (curMonth + 1) > 12){
				// 次年
				int size=max-list.size();
				for (int i = 1; i <=size; i++) {
					int month=(curMonth + 1) % 12;
					list.add("次年"+(month==0?12:month )+ "月" + i+"日");
				}
			}
			else{
				int size=max-list.size();
				for (int i = 1; i <=size; i++) {
					int month=(curMonth + 1) % 12;
					list.add((month==0?12:month ) + "月" + i+"日");
				}
			}

		}
		else{
			for (int i = mDay; i <mDay+ max; i++) {
				list.add(curMonth + "月" + i+"日");
			}
		}
//		addDayList(curYear, curMonth, mDay, false, true);// 第一个月
//		addDayList((curMonth + 1) > 12 ? ((curYear + 1)) : curYear,
//				(curMonth + 1) % 12, mDay, (curMonth + 1) > 12 ? true : false,
//				false);// 第二个月
//		addDayList((curMonth + 2) > 12 ? ((curYear + 1)) : curYear,
//				(curMonth + 2) % 12, mDay, (curMonth + 2) > 12 ? true : false,
//				false);// 第三个月
		NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(
				context, list, "%02d", type);
//		numericWheelAdapter.setLabel("日");
		day.setViewAdapter(numericWheelAdapter);
		day.setCurrentItem(type == 1 ? 1 : 0);
	}

	/**
	 * curYear当前年， curMonth当前月（不包含）
	 */
	private void initDay2(int curYear, int curMonth, int mDay) {
		Log.e("", curYear + "," + curMonth + "," + mDay + "," + mHour + ","
				+ mMinute);
		list.clear();
		int max=5;
		if(getDay(curYear, curMonth)<mDay+max-1){
			addDayList(curYear, curMonth, mDay, false, true);// 第一个月
			if( (curMonth + 1) > 12){
				// 次年
				int size=max-list.size();
				for (int i = 1; i <=size; i++) {
					list.add("次年"+(curMonth + 1) % 12 + "月" + i);
				}
			}
			else{
				int size=max-list.size();
				for (int i = 1; i <=size; i++) {
					list.add((curMonth + 1) % 12 + "月" + i);
				}
			}

		}
		else{
			for (int i = mDay; i <mDay+ max; i++) {
				list.add(curMonth + "月" + i);
			}
		}
//		addDayList(curYear, curMonth, mDay, false, true);// 第一个月
//		addDayList((curMonth + 1) > 12 ? ((curYear + 1)) : curYear,
//				(curMonth + 1) % 12, mDay, (curMonth + 1) > 12 ? true : false,
//				false);// 第二个月
//		addDayList((curMonth + 2) > 12 ? ((curYear + 1)) : curYear,
//				(curMonth + 2) % 12, mDay, (curMonth + 2) > 12 ? true : false,
//				false);// 第三个月
		NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(
				context, list, "%02d", 3);
		numericWheelAdapter.setLabel("日");
		day.setViewAdapter(numericWheelAdapter);
		day.setCurrentItem(1);
	}

	List<String> list = new ArrayList<String>();
	List<String> list_min = new ArrayList<String>();

	private void addDayList(int Year, int Month, int Day, boolean isNextYear,
			boolean isFirstMonth) {
		Month = (Month == 0) ? Month = 12 : Month;
		if (isNextYear) {
			// 次年
			for (int i = 1; i <= getDay(Year, Month); i++) {
				list.add("次年" + Month + "月" + i);
			}
		} else {
			for (int i = (isFirstMonth ? Day : 1); i <= getDay(Year, Month); i++) {
				list.add(Month + "月" + i);
			}
		}
	}

	public static OnDateScrollResultListener mOnDateScrollResultListener;

	/**
	 * 自定义时间滚动结果监听
	 */
	public interface OnDateScrollResultListener {
		public void OnDateScrollResult(List<String> list,List<String> list_min, WheelView day,
				WheelView hour, WheelView min);
	}

	public void setOnDateScrollResultListener(
			OnDateScrollResultListener hOnDateScrollResultListener) {
		mOnDateScrollResultListener = hOnDateScrollResultListener;
	}

	/**
	 * 格式化从时间控件获取的时间,只能格式化（含有月日时分的控件）
	 */
	public String onTimeFormat(String day, int min, int sec) {
		long Time = DateFormat.getTime();
		Calendar mCalendar = Calendar.getInstance();
		mCalendar.setTimeInMillis(Time);
		int year = mCalendar.get(Calendar.YEAR);
		if (day.contains("次年")) {
			year = year + 1;
			day = day.replace("次年", "");
		}
		day=day.replace("日", "");
		String[] days = day.split("月");
		String month = days[0];
		String date = days[1];
		DecimalFormat format = new DecimalFormat("00");
		return year + "-" + (format.format(Integer.parseInt(month))) + "-"
				+ (format.format(Integer.parseInt(date))) + " "
				+ format.format(min) + ":" + format.format(sec);

	}

	/**
	 * 格式化从时间控件获取的时间,只能格式化（含有月日控件）
	 */
	public String onTimeFormat(String day) {
		long Time = DateFormat.getTime();
		Calendar mCalendar = Calendar.getInstance();
		mCalendar.setTimeInMillis(Time);
		DecimalFormat format = new DecimalFormat("00");
		int year = mCalendar.get(Calendar.YEAR);
		if (day.contains("昨天")) {
			Time = Time - 24 * 60 * 60 * 1000;
			mCalendar = Calendar.getInstance();
			mCalendar.setTimeInMillis(Time);
			year = mCalendar.get(Calendar.YEAR);
			return year + "-"
					+ format.format(mCalendar.get(Calendar.MONTH) + 1) + "-"
					+ format.format(mCalendar.get(Calendar.DAY_OF_MONTH));
		}
		if (day.contains("次年")) {
			year = year + 1;
			day = day.replace("次年", "");
		}
		day=day.replace("日", "");
		String[] days = day.split("月");
		String month = days[0];
		String date = days[1];
		return year + "-" + (format.format(Integer.parseInt(month))) + "-"
				+ (format.format(Integer.parseInt(date)));

	}

	/**
	 * 自定义人数滚动结果监听
	 */
	public OnPeopleScrollResultListener mOnPeopleScrollResultListener;

	/**
	 * 自定义人数滚动结果监听
	 */
	public interface OnPeopleScrollResultListener {
		public void OnPeopleScrollResult(WheelView people);
	}

	public void setOnPeopleScrollResultListener(
			OnPeopleScrollResultListener hOnPeopleScrollResultListener) {
		mOnPeopleScrollResultListener = hOnPeopleScrollResultListener;
	}

	/**
	 * 自定义时间确定结果监听
	 */
	public OnDateConfirmListener mOnDateConfirmListener;

	/**
	 * 自定义时间确定结果监听
	 */
	public interface OnDateConfirmListener {
		public void onDateConfirm(List<String> list,List<String> list_min, WheelView day,
				WheelView hour, WheelView min,int estimate_time);
	}

	public void setOnDateConfirmListener(
			OnDateConfirmListener hOnDateConfirmListener) {
		mOnDateConfirmListener = hOnDateConfirmListener;
	}

	/**
	 * 自定义确定结果监听(单个控件，如：人数或者单个日期，，不适用与多个的，如几月几日几时几分)
	 */
	public OnConfirmListener mOnConfirmListener;

	/**
	 * 自定义确定结果监听(单个控件，如：人数或者单个日期，，不适用与多个的，如几月几日几时几分)
	 */
	public interface OnConfirmListener {
		public void onConfirm(List<String> list, WheelView wv);
	}

	public void setOnConfirmListener(OnConfirmListener hOnConfirmListener) {
		mOnConfirmListener = hOnConfirmListener;
	}
	/////////////////
	/**
	 * 自定义PopView开关状态监听
	 */
	 public static ArrayList<OnPoPViewStateListener>  mOnPoPViewStateListenerlist=new ArrayList<OnPoPViewStateListener>();
	/**
	 * 自定义PopView开关状态监听
	 */
	public interface OnPoPViewStateListener {
		
		/**
		 * 自定义时间控件开关状态监听
		 */
		public void onPopViewState(boolean isOpen);
	}

	public static void setOnPoPViewStateListener(OnPoPViewStateListener hOnPoPViewStateListener) {
		mOnPoPViewStateListenerlist.add(hOnPoPViewStateListener);
	}
	public static void removeOnPoPViewStateListener(OnPoPViewStateListener hOnPoPViewStateListener){
		mOnPoPViewStateListenerlist.remove(hOnPoPViewStateListener);
	}
}
